package org.bigjava.novelplatform.common.aopConfig;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.bigjava.novelplatform.vo.UserInfoVo;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

import static org.bigjava.novelplatform.common.constant.NovelInfoConstant.SESSION_USER;

/**
 * @author ykh
 * @create 2022-04-20 12:37
 */
@Aspect
@Component
public class UserControllerAop {
    /**
     * 为Controller的最后一个参数类型为UserInfoVo的参数从session中获取UserInfoVo。
     * @param proceedingJoinPoint
     * @return
     */
    @Around("execution(* org.bigjava.novelplatform.controller.*Controller.*(..,org.bigjava.novelplatform.vo" +
            ".UserInfoVo))")
    public Object addUserInfoVo(ProceedingJoinPoint proceedingJoinPoint) {
        Object proceed = null;
        try {
            //https://docs.spring.io/spring-framework/docs/current/javadoc-api/
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpSession session=attr.getRequest().getSession();
            UserInfoVo user  = (UserInfoVo) session.getAttribute(SESSION_USER);
            Object[] args = proceedingJoinPoint.getArgs();
            args[args.length-1] = user;
            proceed = proceedingJoinPoint.proceed(args);
        } catch (RuntimeException e){
            throw e;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        return proceed;
    }
}
